package com.icms.web.admin;

import com.icms.common.basic.AdminController;
import com.icms.common.config.AppConst;
import com.icms.common.shiro.ShiroUtil;
import com.icms.common.util.DbTableUtil;
import com.icms.core.model.Model;
import com.icms.core.service.ModelService;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Page;

public class ModelController extends AdminController {

	public void index() {
		Integer siteId = (Integer) ShiroUtil.getSessionAttr(AppConst.SITE_ID);
		Integer pageNumber = getParaToInt(0, 1);
		Page<Model> page = ModelService.service.getModelPageBySiteId(pageNumber, siteId);
		setAttr("page", page);
		renderAdmin("model-list");
	}

	public void input() {
		Integer modelId = getParaToInt(0);
		if (modelId != null) {
			Model model = ModelService.service.getModelByModelId(modelId);
			setAttr("model", model);
		}
		renderAdmin("model-input");
	}

	public void save() {
		Model model = getModel(Model.class);
		boolean status = DbTableUtil.initTable(model.getTableName());
		LogKit.info("process :" + status);
		if (ModelService.service.AddOrUpdateModel(model)) {
			renderSuccess("操作成功");
		} else {
			renderError("操作失败");
		}
	}

	public void del() {
		Integer modelId = getParaToInt(0);
		String tableName = ModelService.service.getModelByModelId(modelId).getTableName();
		if (ModelService.service.deleteByModelId(modelId)) {
			DbTableUtil.dropDbtable(tableName);
			renderJson(true);
		} else {
			renderJson(false);
		}
	}

	public void status() {
		int modelId = getParaToInt(0);
		Model model = ModelService.service.getModelByModelId(modelId);
		if (model.getStatus()) {
			model.setStatus(false);
		} else {
			model.setStatus(true);
		}
		ModelService.service.AddOrUpdateModel(model);
		renderJson(true);
	}

	public void validateModelname() {
		String modelName = getPara("model.model_name");
		if (ModelService.service.getModelByModelName(modelName) == null) {
			renderJson("true");
		} else {
			renderJson("false");
		}
	}

	public void validateTablename() {
		String tableName = getPara("model.table_name");
		if (ModelService.service.getModelByModelName(tableName) == null) {
			renderJson("true");
		} else {
			renderJson("false");
		}
	}

}
